package org.bob.learn.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.bob.learn.common.util.JacksonUtils;
import org.bob.learn.dao.entity.Student;
import org.bob.learn.dao.repository.StudentRepository;
import org.bob.learn.service.StudentService;
import org.bob.learn.web.model.StudentCriteria;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import static org.bob.learn.common.util.SQLMapper.map;

/**
 * 学生服务实现类
 */
@Slf4j
@Service
public class StudentServiceImpl implements StudentService {

    private final DatabaseClient databaseClient;

    private final StudentRepository studentRepository;

    public StudentServiceImpl(DatabaseClient databaseClient, StudentRepository studentRepository) {
        this.databaseClient = databaseClient;
        this.studentRepository = studentRepository;
    }

    /**
     * 逻辑说明：异步逻辑->同步逻辑-副作用（打印日志）
     * 使用方法：doOnNext
     * @param id 学生标识
     * @return 学生信息
     */
    @Override
    public Mono<Student> queryById(Long id) {
        return studentRepository.findById(id).doOnNext(student -> log.info("查询学生信息[{}]", JacksonUtils.toJson(student)));
    }

    /**
     * 基于databaseClient实现动态复杂查询
     * @param criteria 查询条件
     * @return 学生信息列表
     */
    @Override
    public Flux<Student> queryByCriteria(StudentCriteria criteria) {
        return databaseClient.sql(map("SELECT * FROM student WHERE 1=1",criteria)).mapProperties(Student.class).all();
    }
}
